const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const ResponseHelper = require('../utils/response');
const ServiceDepositPrisma = require('../models/ServiceDepositPrisma');
const LocalServicePrisma = require('../models/LocalServicePrisma');
const WechatPayService = require('../utils/WechatPayService');

// 获取用户保证金余额
router.get('/balance', authenticateToken, async (req, res) => {
  try {
    const balance = await ServiceDepositPrisma.getUserDepositBalance(req.user.id);
    return ResponseHelper.success(res, { balance }, '获取保证金余额成功');
  } catch (err) {
    console.error('获取保证金余额失败:', err);
    return ResponseHelper.serverError(res, '获取保证金余额失败', err);
  }
});

// 获取用户保证金记录
router.get('/records', authenticateToken, async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      operation_type,
      status
    } = req.query;

    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      operation_type,
      status
    };

    const result = await ServiceDepositPrisma.findByUserId(req.user.id, options);

    return ResponseHelper.success(res, {
      items: result.deposits,
      total: result.total,
      page: parseInt(page),
      limit: parseInt(limit)
    }, '获取保证金记录成功');
  } catch (err) {
    console.error('获取保证金记录失败:', err);
    return ResponseHelper.serverError(res, '获取保证金记录失败', err);
  }
});

// 充值保证金
router.post('/deposit', authenticateToken, async (req, res) => {
  try {
    const { amount, service_id } = req.body;

    // 验证金额
    if (!amount || amount <= 0) {
      return ResponseHelper.error(res, '请输入有效的充值金额', 400);
    }

    // 如果指定了服务ID，验证服务存在且属于当前用户
    if (service_id) {
      const service = await LocalServicePrisma.findById(service_id);
      if (!service) {
        return ResponseHelper.error(res, '指定的服务不存在', 400);
      }
      if (service.user_id.toString() !== req.user.id.toString()) {
        return ResponseHelper.forbidden(res, '无权限操作此服务');
      }
    }

    // 创建保证金充值记录
    const depositData = {
      user_id: req.user.id,
      service_id: service_id || null,
      amount: amount,
      deposit_type: service_id ? 'SERVICE' : 'GLOBAL',
      operation_type: 'DEPOSIT',
      status: 'PENDING'
    };

    const deposit = await ServiceDepositPrisma.create(depositData);

    // 创建支付订单号
    const orderNumber = `DEPOSIT_${deposit.id}_${Date.now()}`;
    const _paymentDescription = service_id ? '服务保证金充值' : '全局保证金充值';

    // 更新保证金记录的交易ID
    await deposit.updateStatus('PENDING', orderNumber);

    // 检查是否是模拟支付模式
    if (process.env.WECHAT_PAY_MOCK_MODE === 'true' || process.env.NODE_ENV === 'development') {
      return ResponseHelper.success(res, {
        deposit: deposit,
        payment_params: {
          mockMode: true,
          orderNumber
        }
      }, '创建充值订单成功（模拟模式）');
    } else {
      // 真实支付模式 - 这里需要实际的微信支付集成
      return ResponseHelper.success(res, {
        deposit: deposit,
        payment_params: {
          mockMode: true, // 暂时使用模拟模式
          orderNumber
        }
      }, '创建充值订单成功');
    }
  } catch (err) {
    console.error('充值保证金失败:', err);
    return ResponseHelper.serverError(res, '充值保证金失败', err);
  }
});

// 申请退款
router.post('/refund', authenticateToken, async (req, res) => {
  try {
    const { amount, service_id, refund_reason } = req.body;

    // 验证金额
    if (!amount || amount <= 0) {
      return ResponseHelper.error(res, '请输入有效的退款金额', 400);
    }

    // 验证退款原因
    if (!refund_reason || refund_reason.trim().length < 5) {
      return ResponseHelper.error(res, '请填写详细的退款原因（至少5个字符）', 400);
    }

    // 检查用户余额是否足够
    const userBalance = await ServiceDepositPrisma.getUserDepositBalance(req.user.id);
    if (userBalance < amount) {
      return ResponseHelper.error(res, `余额不足，当前余额：${userBalance}元，申请退款：${amount}元`, 400);
    }

    // 如果指定了服务ID，验证服务存在且属于当前用户
    if (service_id) {
      const service = await LocalServicePrisma.findById(service_id);
      if (!service) {
        return ResponseHelper.error(res, '指定的服务不存在', 400);
      }
      if (service.user_id.toString() !== req.user.id.toString()) {
        return ResponseHelper.forbidden(res, '无权限操作此服务');
      }
      
      // 检查服务的保证金余额
      if (Number(service.deposit_paid) < amount) {
        return ResponseHelper.error(res, `服务保证金余额不足，当前余额：${service.deposit_paid}元`, 400);
      }
    }

    // 创建保证金退款记录
    const refundData = {
      user_id: req.user.id,
      service_id: service_id || null,
      amount: amount,
      deposit_type: service_id ? 'SERVICE' : 'GLOBAL',
      operation_type: 'REFUND',
      status: 'PENDING',
      refund_reason: refund_reason.trim()
    };

    const refund = await ServiceDepositPrisma.create(refundData);

    return ResponseHelper.success(res, refund, '退款申请提交成功，请等待审核');
  } catch (err) {
    console.error('申请退款失败:', err);
    return ResponseHelper.serverError(res, '申请退款失败', err);
  }
});

// 支付回调处理（微信支付回调）
router.post('/payment/callback', async (req, res) => {
  try {
    // 验证微信支付回调签名
    const isValid = WechatPayService.verifyNotification(req.body, req.headers);
    
    if (!isValid) {
      return res.status(400).json({ code: 'FAIL', message: '签名验证失败' });
    }

    const { out_trade_no, transaction_id, trade_state } = req.body.resource.ciphertext;

    // 解析订单号获取保证金记录ID
    const orderParts = out_trade_no.split('_');
    if (orderParts.length < 2 || orderParts[0] !== 'DEPOSIT') {
      return res.status(400).json({ code: 'FAIL', message: '无效的订单号' });
    }

    const depositId = orderParts[1];
    const deposit = await ServiceDepositPrisma.findById(depositId);

    if (!deposit) {
      return res.status(404).json({ code: 'FAIL', message: '保证金记录不存在' });
    }

    // 处理支付结果
    if (trade_state === 'SUCCESS') {
      await deposit.completeDeposit(transaction_id);
      console.log(`保证金充值成功：用户${deposit.user_id}，金额${deposit.amount}元`);
    } else {
      await deposit.updateStatus('FAILED', transaction_id);
      console.log(`保证金充值失败：用户${deposit.user_id}，金额${deposit.amount}元`);
    }

    res.json({ code: 'SUCCESS', message: 'OK' });
  } catch (err) {
    console.error('处理支付回调失败:', err);
    res.status(500).json({ code: 'FAIL', message: '处理失败' });
  }
});

// 模拟支付完成（仅在开发环境使用）
router.post('/payment/mock-success', authenticateToken, async (req, res) => {
  try {
    if (process.env.NODE_ENV === 'production') {
      return ResponseHelper.forbidden(res, '生产环境不允许使用此接口');
    }

    const { order_number } = req.body;

    if (!order_number) {
      return ResponseHelper.error(res, '请提供订单号', 400);
    }

    // 解析订单号获取保证金记录ID
    const orderParts = order_number.split('_');
    if (orderParts.length < 2 || orderParts[0] !== 'DEPOSIT') {
      return ResponseHelper.error(res, '无效的订单号', 400);
    }

    const depositId = orderParts[1];
    const deposit = await ServiceDepositPrisma.findById(depositId);

    if (!deposit) {
      return ResponseHelper.notFound(res, '保证金记录不存在');
    }

    // 检查权限
    if (deposit.user_id.toString() !== req.user.id.toString()) {
      return ResponseHelper.forbidden(res, '无权限操作此记录');
    }

    // 模拟支付成功
    const mockTransactionId = `MOCK_${Date.now()}`;
    await deposit.completeDeposit(mockTransactionId);

    return ResponseHelper.success(res, deposit, '模拟支付成功');
  } catch (err) {
    console.error('模拟支付失败:', err);
    return ResponseHelper.serverError(res, '模拟支付失败', err);
  }
});

module.exports = router;